package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.exception.LoginException;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.repository.UserInfoRepository;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.AssertUtil;
import cn.wolfcode.wolf2w.util.Consts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.UUID;

/**
 * Created by 甘静斌 on 2020-08-07 13:41
 */
@Service
//@Transactional
public class UserInfoServiceImpl implements IUserInfoService {

    @Autowired
    private UserInfoRepository repository;

    @Autowired
    private IUserInfoRedisService userInfoRedisService;




    @Override
    public void save(UserInfo userInfo) {

        repository.save(userInfo);
    }

    @Override
    public void update(UserInfo userInfo) {

        repository.save(userInfo);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public UserInfo get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<UserInfo> list() {
        return repository.findAll();
    }

    @Override
    public boolean checkPhone(String phone) {

        UserInfo userInfo = repository.findByphone(phone);
        return userInfo == null;
    }

    /**
     * 短信验证码操作
     * @param phone
     */
    @Override
    public void sendVerifyCode(String phone) {

        //创建验证码
        String code = UUID.randomUUID().toString().replaceAll("-", "")
                .substring(0, 4);
        //创建短信
        StringBuilder sb = new StringBuilder(80);
        sb.append("【创信】您注册的短信验证码是:").append(code).append(",请在")
                .append(Consts.VERIFY_CODE_VAI_TIME).append("分钟内使用");

        //发送
        System.out.println(sb);
        //真实发送短信就是使用java发起http请求即可
        //Springmvc提供一个工具类:RestTemplate 用于发送http请求
       /*
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://way.jd.com/chuangxin/dxjk?mobile={1}&content={2}&appkey={3}";
        //参数1:短信接口url
        //参数2:请求接口完成之后响应数据封装对象类型
        //参数3:请求参数列表
        String ret = restTemplate.getForObject(url, String.class, phone, sb.toString(), "484e84d31ec2a0911208d9e7004efe68");

        if (!ret.contains("Success")){
            throw new LoginException("短信发送肆佰");
        }
*/

        //将验证码缓存到redis中
        userInfoRedisService.setVerifyCode(phone,code);

    }

    /**
     * 设置用户注册校验-异常操作
     * @param phone
     * @param nickname
     * @param password
     * @param rpassword
     * @param verifyCode
     */
    @Override
    public void regist(String phone, String nickname, String password, String rpassword, String verifyCode) {

        //校验参数是否为空
        AssertUtil.hasLength(phone, "手机号不能为空");
        AssertUtil.hasLength(nickname, "昵称不能为空");
        AssertUtil.hasLength(password, "密码不能为空");
        AssertUtil.hasLength(rpassword, "密码确认不能为空");
        AssertUtil.hasLength(verifyCode, "验证码不能为空");
        //校验2次输入密码是否相等
        AssertUtil.isEquals(password,rpassword,"两次输入密码不相等");
        //校验手机号是否唯一
        if (!this.checkPhone(phone)){
            throw new LoginException("该手机号已被注册过了");
        }
        //校验短信验证码是否正确
        String code = userInfoRedisService.getVerifyCode(phone);

        if (!code.equals(verifyCode)){
            throw new LoginException("验证码不正确");
        }

        //注册
        UserInfo userInfo = new UserInfo();
        userInfo.setNickname(nickname);
        userInfo.setPhone(phone);
        userInfo.setEmail("");
        userInfo.setPassword(password);
        userInfo.setLevel(1);
        userInfo.setCity("");
        userInfo.setHeadImgUrl("/images/default.jpg");
        userInfo.setInfo("");

        userInfo.setState(UserInfo.STATE_NORMAL); //设置完成注册后状态是正常的
        //保存信息
        this.save(userInfo);
    }

    @Override
    public UserInfo findByUsernameAndPassword(String username, String password) {

        //操作数据库,获取用户名和密码
        UserInfo user = repository.findByphone(username);
        if (user == null || !user.getPassword().equals(password)){
            throw new RuntimeException("账号或者密码错误");
        }
        //设置密码为空
        user.setPassword("");
        return user;
    }

    @Override
    public List<UserInfo> queryByCity(String name) {
        return repository.findByCity(name);
    }
}
